from rest_framework import viewsets, status
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import City, IDC, Host
from .serializers import CitySerializer, IDCSerializer, HostSerializer
import subprocess
import platform


# CRUD接口
class CityViewSet(viewsets.ModelViewSet):
    queryset = City.objects.all()
    serializer_class = CitySerializer


class IDCViewSet(viewsets.ModelViewSet):
    queryset = IDC.objects.all()
    serializer_class = IDCSerializer


class HostViewSet(viewsets.ModelViewSet):
    queryset = Host.objects.all()
    serializer_class = HostSerializer


# Ping探测接口
class PingHostAPIView(APIView):
    def get(self, request, host_id):
        try:
            host = Host.objects.get(id=host_id)
        except Host.DoesNotExist:
            return Response({"error": "主机不存在"}, status=status.HTTP_404_NOT_FOUND)

        # 根据操作系统选择合适的ping命令参数
        if platform.system().lower() == "windows":
            # Windows环境下ping命令参数
            cmd = ["ping", "-n", "1", "-w", "2000", host.ip]  # 1个包，超时2秒(2000毫秒)
        else:
            # Linux/Mac环境下ping命令参数
            cmd = ["ping", "-c", "1", "-W", "2", host.ip]  # 1个包，超时2秒
        
        # 执行ping命令
        result = subprocess.run(
            cmd,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE
        )
        return Response({
            "host_id": host.id,
            "ip": host.ip,
            "reachable": result.returncode == 0  # 0表示可达
        })